package my.java.io.fileconvertor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import my.base.io.EncodingDetect;
import my.java.io.FileConvertor;
import my.java.io.StringFilter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class GeneralFileConvertor implements FileConvertor {
	private static final Log logger = LogFactory.getLog(GeneralFileConvertor.class);
	
	private StringFilter filter = null;

	public GeneralFileConvertor(StringFilter filter) {
		this.filter = filter;
	}

	public void convert(File inputFile, String outputFilePath) {
		logger.info("convert " + inputFile + " " + outputFilePath);
		BufferedReader bufferedReader = null;
		PrintWriter printWriter = null;
		int linenumber = 0;
		try {
			String encode = EncodingDetect.getJavaEncode(inputFile.getAbsolutePath());
			logger.info(inputFile.getAbsoluteFile() + " encode " + encode);
			bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), encode));
			
			printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath), encode)),true);
			String temp = bufferedReader.readLine();
			while (temp != null) {
				System.out.println(temp);
				linenumber++;
				String out = filter.convert(temp);
				if (out != null) {
					printWriter.println(out);
				}
				temp = bufferedReader.readLine();
			}
			logger.info(inputFile.getName() + " total line " + linenumber);
			bufferedReader.close();
			printWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
